/*
 * Main.java
 *
 * Created on September 18, 2007, 9:12 AM
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */
package jia.editor;

import com.ibatis.common.resources.Resources;
import com.ibatis.sqlmap.client.SqlMapClient;
import com.ibatis.sqlmap.client.SqlMapClientBuilder;
import java.awt.Component;
import java.io.File;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import javax.swing.JOptionPane;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.metal.OceanTheme;
import jia.game.GenericFlags;
import org.apache.log4j.Logger;

/**
 *
 * @author estell
 */
public class EditorMain {

    private static final Logger log = Logger.getLogger(EditorMain.class);
    //create single static instances of all panels for the editor.  This is done
    //to prevent constant loading and reloading of new panels every time someone
    //clicks a button.  I dont trust the JRE's memory management.
    public static DefaultPanel p_defaultAdminPanel;
    public static EditorMainFrame p_mainFrame;
    public static String designName;
    public static int designId;
    public static String databaseDriver = "org.apache.derby.jdbc.EmbeddedDriver";
    public static String databaseProtocol = "jdbc:derby:";
    public static SqlMapClient sqlMap;

    /** Creates a new instance of Main */
    public EditorMain() {
    }

    private static int showError(Component c) {
        String msg = "The database could not be located.  This is either because:\r\n\r\n1. this is the first time you are loading JIA,\r\n\r\nor\r\n\r\n2.  The database was removed somehow.\r\n\r\nWould you like me to reload it?";
        //JOptionPane optionPane = new JOptionPane("yadda yadda", JOptionPane.QUESTION_MESSAGE, JOptionPane.YES_NO_OPTION);
        //optionPane.setVisible(true);
        return JOptionPane.showConfirmDialog(c, msg, "Database Note Found!", JOptionPane.OK_CANCEL_OPTION);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        boolean shouldIReload = false;
        EditorMainFrame mainFrame = new EditorMainFrame();
        p_mainFrame = mainFrame;


        String resource = "jia/persist/SqlMapConfig.xml";
        Reader reader = null;
        try {
            reader = Resources.getResourceAsReader(resource);
        } catch (IOException ex) {
            System.out.println("Reader not loaded");
            //log.error(ex);
            ex.printStackTrace();
        }

        try {
            sqlMap = SqlMapClientBuilder.buildSqlMapClient(reader);
            if (sqlMap != null) {
                System.out.println("The database was loaded!");

            } else {
                System.out.println("SQL Map was null");
            }
        } catch (Exception e) {
            System.out.println("An error occured while loading the database");
            //log.error(e);
        }


        try {
            File testFile = new File("database/JIA");
            System.out.println("Loading database file");

            if (testFile == null || !testFile.isDirectory()) { //if the database is null or not a directory
                if (GenericFlags.errorMessages) {
                    System.out.println("The database was not found!");
                }
                int n = showError(mainFrame);

                if (n == 0) {
                    if (GenericFlags.warningMessages) {
                        System.out.println("reloading the database");
                    }
                    //the user wants to reload the database
                    Class.forName(databaseDriver).newInstance();
                    Connection conn = DriverManager.getConnection(databaseProtocol + "database/JIA;create=true;user=jiauser;password=jiauser");

                    if (conn == null){
                         if (GenericFlags.errorMessages){
                             log.error("The connection to the database was not established!");
                         }

                    }else{
                    //TODO:  further process that loads in a default database schema to rebuild the tables
                     }

                    buildPanels();
                    mainFrame.setContentPane(p_defaultAdminPanel);
                    mainFrame.getContentPane().setVisible(true);
                    mainFrame.show();

                } else {
                    if (GenericFlags.errorMessages) {
                        log.error("Exiting application!");
                    }
                    mainFrame.dispose();
                }

            } else { //the database was not null, so proceed as normal
//                Class.forName(databaseDriver).newInstance();
//                Connection conn = DriverManager.getConnection(databaseProtocol + "database/JIA;create=true;user=jiauser;password=jiauser");
//
//                log.error("Created a connection object");
//                if (conn == null) {
//                    if (GenericFlags.errorMessages) {
//                        log.error("The connection to the database was not established!");
//                    }
//                    mainFrame.dispose();
//
//                } else {
//                    if (GenericFlags.warningMessages) {
//                        log.warn("Database loaded Normally!");
//                    }
//                }

                buildPanels();
                mainFrame.setContentPane(p_defaultAdminPanel);
                mainFrame.getContentPane().setVisible(true);
                mainFrame.show();
            }
//
//
//        } catch (IllegalAccessException ex) {
//
//            if (GenericFlags.errorMessages) {
//                log.error(ex.getMessage());
//            }
//        } catch (ClassNotFoundException ex) {
//            if (GenericFlags.errorMessages) {
//                log.error(ex.getMessage());
//            }
//        } catch (InstantiationException ex) {
//            if (GenericFlags.errorMessages) {
//                log.error(ex.getMessage());
//            }
//        } catch (SQLException ex) {
//            if (GenericFlags.errorMessages) {
//                log.error(ex.getMessage());
//            }

        } catch (Exception e) {
        }
    }

    private static void buildPanels() {
        p_defaultAdminPanel = new DefaultPanel();

        try {
            UIManager.setLookAndFeel("javax.swing.plaf.metal.MetalLookAndFeel");
            MetalLookAndFeel.setCurrentTheme(new OceanTheme());
        } catch (UnsupportedLookAndFeelException e) {
            if (GenericFlags.errorMessages) {
                log.error(e.getMessage());
            }
        } catch (ClassNotFoundException e) {
            if (GenericFlags.errorMessages) {
                log.error(e.getMessage());
            }
        } catch (InstantiationException e) {
            if (GenericFlags.errorMessages) {
                log.error(e.getMessage());
            }
        } catch (IllegalAccessException e) {
            if (GenericFlags.errorMessages) {
                log.error(e.getMessage());
            }
        }



    }

    public static String getDesignName() {
        return designName;
    }

    public static int getDesignId() {
        return designId;
    }

    public static void setDesignName(String newDesign) {
        designName = newDesign;
    }

    public static void setDesignId(int newDesignId) {
        designId = newDesignId;

    }
}
